package com.niuke;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

/**
 * 48. 最小传输时延
 * https://blog.csdn.net/github_39502869/article/details/131989298
 */
public class NiukeMoni48 {

    public static Map<Integer, Set<Integer>> map = new HashMap<>();
    public static Map<String, Integer> yanShiMap = new HashMap<>();
    public static int res = -1;

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String[] line1 = scanner.nextLine().split(" ");
        int n = Integer.parseInt(line1[0]); // 节点数
        int m = Integer.parseInt(line1[1]); // 从某个节点到某个节点 延时数量

        for (int i = 0; i < m; i++) {
            String[] line = scanner.nextLine().split(" ");
            int node1 = Integer.parseInt(line[0]);
            int node2 = Integer.parseInt(line[1]);
            int yanShi = Integer.parseInt(line[2]);

            Set<Integer> list = map.getOrDefault(node1, new HashSet<>());
            list.add(node2);
            map.put(node1, list);

            yanShiMap.put(node1 + "-" + node2, yanShi);
        }

        String[] lineEnd = scanner.nextLine().split(" ");
        int startNode = Integer.parseInt(lineEnd[0]); // 开始节点
        int endNode = Integer.parseInt(lineEnd[1]); // 目标节点

        dfs(startNode, endNode, 0);

        System.out.println(res);

    }

    public static void dfs(int startNode, int endNode, int tempYanShi) {
        Set<Integer> next = map.get(startNode);
        if (next == null || next.isEmpty()) {
            res = Math.max(res, -1);
            return;
        }

        int currYanShi = tempYanShi;

        for (Integer node : next) {
            if (node == endNode) {
                if (res == -1) {
                    res = currYanShi + yanShiMap.get(startNode + "-" + endNode);
                } else {
                    res = Math.min(res, currYanShi + yanShiMap.get(startNode + "-" + endNode));
                }
            } else {
                tempYanShi = currYanShi + yanShiMap.get(startNode + "-" + node);
                dfs(node, endNode, tempYanShi);
            }
        }
    }

}
